const express = require('express'),
    db = require('../db'),
    router = express();

router.post('/article/add', (req, res, next) => {
    let article = { createTime: new Date(), updateTime: new Date() };
    db.User.find({ username: req.body.username }).exec((err, data) => {
        article = Object.assign(req.body, article, { user: data[0]._id });
        new db.Article(article).save((err, data) => {
            if (err) {
                res.json({ code: "error", message: "添加失败!" });
            } else {

                res.json({ code: "success", data: data, message: "添加成功！" });
            }
        })
    })
})
router.post('/article/edit/:id', (req, res, next) => {
    console.log(req.params.id)
    var data = {
        title: req.body.title,
        article: req.body.article,
        updateTime: new Date()
    };
    db.Article.findByIdAndUpdate(req.params.id, data, err => {
        if (err) {
            res.json({ code: "error", message: "系统错误!", data: data });
        }
        else {
            res.json({ code: "success", message: "成功！", data: data });
        }
    })
})
router.get('/article/list', (req, res, next) => {
    let page = isNaN(req.query.page) ? 1 : parseInt(req.query.page);
    let pageSize = isNaN(req.query.pagesize) ? 10 : parseInt(req.query.pagesize);
    db.Article.find().count((err, total) => {
        if (err) {
            res.json({ code: 'error', message: '系统错误！' });
            return;
        }
        console.log(total)
        let pageCount = Math.ceil(total / pageSize);

        if (page > pageCount) page = pageCount;
        if (page < 1) page = 1;

        db.Article.find()
            .sort({ _id: 1 }) // 排序
            .skip((page - 1) * pageSize) // 跨过
            .limit(pageSize) // 限制取记录数
            .exec((err, data) => {
                if (err) {
                    res.json({ code: 'error', message: '系统错误！' });
                    return;
                }
                res.json({
                    code: 'success', data: data, nav: {
                        page,
                        total: total,
                        pagesize:pageSize,
                        prev: page - 1, //上一页
                        next: page + 1  //下一页
                    }
                })
            })
    })
})

// // 获取分页页数数组数据
// function getPages(page, pageCount) {
//     let pages = [page]
//     let left = page - 1
//     let right = page + 1
//     while (pages.length < 10 && (left >= 1 || right <= pageCount)) {
//         if (left > 0) pages.unshift(left--)
//         if (right <= pageCount) pages.push(right++)
//     }

//     return pages
// }
module.exports = router;